<?php

namespace App\Services;

use App\User;
use Naux\Mail\SendCloudException;
use Naux\Mail\SendCloudTemplate;
use Mail;

class EmailService{
    /**
     * 发送邮件
     * @param string $type verify_email|find_password
     * @param string $to_email
     * @param array $data
     * @return bool
     */
    public function sendCloudEmail($type = '', $to_email = '', $data = []){

        $verify_email_template = config('SEND_CLOUD_VERIFY_EMAIL_TEMPLATE'); //验证邮件模板
        $find_password_template = config('SEND_CLOUD_FIND_PASSWORD_TEMPLATE'); //找回密码模板

        $_template = '';
        switch ($type){
            case 'verify_email':
                $_template = $verify_email_template;
                break;
            case 'find_password':
                $_template = $find_password_template;
                break;
            default:
                return false;
        }

        $template = new SendCloudTemplate($_template, $data);

        try{
            $resault = Mail::raw($template, function ($message) use ($to_email) {
                $message->from(config('SEND_CLOUD_FROM_EMAIL'), config('SEND_CLOUD_FROM_NAME'));
                $message->to($to_email);
            });

            return true;
        }catch (SendCloudException $exception){
//            dump($exception->getMessage());
            return false;
        }
    }

    /**
     * 验证邮箱
     * @param $token
     * @return bool
     */
    public function verifyEmail($token){
        $user = User::where('confirm_token', $token)->first();
        if (is_null($user)){
            return false;
        }

        $user->is_active = 1;
        $user->confirm_token = str_random(40);
        $user->save();

        return $user;
    }
}